package com.eostoken.eos_wallet.ui.activity;


import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.bean.EOSPrice;
import com.eostoken.eos_wallet.bean.RealTimeIndexBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.EOSNetWorkManager;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.net.common.RxSubscriber;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.eostoken.eos_wallet.utils.Constants.BALANCE;
import static com.eostoken.eos_wallet.utils.Constants.EOSIO_TOKEN_CONTRACT_CODE;
import static com.eostoken.eos_wallet.utils.Constants.MGP_SYMBOL;
import static com.eostoken.eos_wallet.utils.Constants.PRICE;
import static com.eostoken.eos_wallet.utils.Constants.TEALTIME_INDEX;
import static com.eostoken.eos_wallet.utils.Constants.bdCurrencyAmount;

public class RealTimeDateActivity extends BaseActivity<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {


    @BindView(R.id.topBar)
    QMUITopBar topbar;
    @BindView(R.id.tv_allTotal_coins)
    TextView tvAllTotalCoins;
    @BindView(R.id.tv_allTotal_coins_usd)
    TextView tvAllTotalCoinsUsd;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.layout1)
    RelativeLayout layout1;
    @BindView(R.id.tv_cumulative_destruction)
    TextView tvCumulativeDestruction;
    @BindView(R.id.ll_cumulative_destruction)
    LinearLayout llCumulativeDestruction;
    @BindView(R.id.tv_real_time_price)
    TextView tvRealTimePrice;
    @BindView(R.id.tv_real_time_circulation)
    TextView tvRealTimeCirculation;
    @BindView(R.id.tv_market_value_of_circulation)
    TextView tvMarketValueOfCirculation;
    @BindView(R.id.tv_all_network_mortgage)
    TextView tvAllNetworkMortgage;
    @BindView(R.id.tv_mortgage_value)
    TextView tvMortgageValue;
    @BindView(R.id.tv_operation_and_construction)
    TextView tvOperationAndConstruction;
    @BindView(R.id.ll_yunying)
    LinearLayout llYunying;
    @BindView(R.id.tv_ecological_construction)
    TextView tvEcologicalConstruction;
    @BindView(R.id.tv_ecological_fund)
    TextView tvEcologicalFund;
    @BindView(R.id.ll_shengtai)
    LinearLayout llShengtai;
    @BindView(R.id.tv_team_motivation)
    TextView tvTeamMotivation;
    @BindView(R.id.ll_tuandui)
    LinearLayout llTuandui;
    @BindView(R.id.appsItemLayout)
    QMUILinearLayout appsItemLayout;
    @BindView(R.id.mappingIndexTv)
    TextView mappingIndexTv;
    @BindView(R.id.tv_latest_block)
    TextView tvLatestBlock;
    @BindView(R.id.tv_block_reward)
    TextView tvBlockReward;
    @BindView(R.id.tv_produced)
    TextView tvProduced;
    @BindView(R.id.tv_surplus_produced)
    TextView tvSurplusProduced;
    @BindView(R.id.ll_LatestBlock)
    LinearLayout llLatestBlock;
    @BindView(R.id.ll_BlockReward)
    LinearLayout llBlockReward;
    @BindView(R.id.ll_produced)
    LinearLayout llProduced;
    @BindView(R.id.ll_surplusProduced)
    LinearLayout llSurplusProduced;

    private RealTimeIndexBean realTimeIndexBean;
    private MgpWallet wallet;
    private String accountName;
    private BigDecimal balance = BigDecimal.ZERO;
    private BigDecimal price = BigDecimal.ZERO;
    private BigDecimal bdDestruction = new BigDecimal("2100000");
    private BigDecimal bdMiningpool = new BigDecimal("350000000");
    private BigDecimal bdRealtimeCirculation = BigDecimal.ZERO;
    private BigDecimal bdSoTheMortgage = BigDecimal.ZERO;
    private BigDecimal bdOperatingFunds = BigDecimal.ZERO;
    private BigDecimal bdNikkoEcoFund = BigDecimal.ZERO;
    private BigDecimal bdEcologicalReward = BigDecimal.ZERO;
    private BigDecimal bdMagpchain2222 = BigDecimal.ZERO;
    private BigDecimal bdAccumulativeDestruction = BigDecimal.ZERO;
    private boolean isPrice = false;//价格
    private boolean isSoTheMortgage = false;//全网抵押
    private boolean isOperatingFunds = false;//运营基金
    private boolean isNikkoEcoFund = false;//生态基金
    private boolean isEcologicalReward = false;//生态奖励
    private boolean isMagpchain2222 = false;//magpchain2222
    private boolean isAccumulativeDestruction = false;//累计销毁

    private void realtimeCirculation() {
        //实时流通 = 总量 - 全网抵押 -（运营基金 + 生态基金 + 生态奖励）-magpchain2222-矿池
        if (isSoTheMortgage && isOperatingFunds && isNikkoEcoFund && isEcologicalReward && isMagpchain2222 && isAccumulativeDestruction && isPrice) {
            bdRealtimeCirculation = bdCurrencyAmount.subtract(bdMiningpool).subtract(bdDestruction)
                    .subtract(bdSoTheMortgage).subtract(bdOperatingFunds).subtract(bdNikkoEcoFund)
                    .subtract(bdEcologicalReward).subtract(bdMagpchain2222).subtract(bdAccumulativeDestruction);
//
//            LogUtils.dTag("realtimeCirculation==", bdCurrencyAmount.toPlainString()
//                    + "-" + bdMiningpool.toPlainString()
//                    + "-" + bdDestruction.toPlainString()
//                    + "-" + bdSoTheMortgage.toPlainString()
//                    + "-" + bdOperatingFunds.toPlainString()
//                    + "-" + bdNikkoEcoFund.toPlainString()
//                    + "-" + bdEcologicalReward.toPlainString()
//                    + "-" + bdMagpchain2222.toPlainString()
//                    + "-" + bdAccumulativeDestruction.toPlainString()
//                    + "=" + bdCurrencyAmount.subtract(bdMiningpool).subtract(bdDestruction)
//                    .subtract(bdSoTheMortgage).subtract(bdOperatingFunds).subtract(bdNikkoEcoFund)
//                    .subtract(bdEcologicalReward).subtract(bdMagpchain2222).subtract(bdAccumulativeDestruction));
            tvAllTotalCoins.setText(bdCurrencyAmount.subtract(bdAccumulativeDestruction).toPlainString());
            tvAllTotalCoinsUsd.setText("$" + (bdCurrencyAmount.subtract(bdAccumulativeDestruction)).multiply(price).toPlainString());

            tvRealTimeCirculation.setText(bdRealtimeCirculation.toPlainString());
            tvMarketValueOfCirculation.setText("$" + bdRealtimeCirculation.multiply(price).setScale(2, RoundingMode.FLOOR).toPlainString());

        }
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_real_time_date;
    }

    @Override
    protected void initData() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        wallet = WalletUtils.getCurrentWallet(this);
        accountName = wallet.getCurrentAccountName();
        presenter.requestPortData(Constants.PRICE_MGP, PRICE);
        presenter.requestPortData("", TEALTIME_INDEX);
        presenter.requestCurrencyBalance(Params.getBalancePamars(accountName, EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL));
//地址:mangochain11 生态激励地址 47700000
//地址:mangochain22 生态基金地址  46760000
//地址:mangochain33 运营地址 9769290
        //实时流通 = 总量 - 全网抵押 -（运营基金 + 生态基金 + 生态奖励）-magpchain2222-矿池
        getCurrencyBalance(Params.getBalancePamars("mangochain11", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL), 1);
        getCurrencyBalance(Params.getBalancePamars("mangochain22", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL), 2);
        getCurrencyBalance(Params.getBalancePamars("mangochain33", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL), 3);
        getCurrencyBalance(Params.getBalancePamars("mgpchain2222", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL), 4);
        getCurrencyBalance(Params.getBalancePamars("eosio.token", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL), 5);
    }

    @Override
    public void initView() {
        topbar.setTitle(StringUtils.getString(R.string.str_real_time_data));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        llLatestBlock.setVisibility(View.GONE);
        llBlockReward.setVisibility(View.GONE);
        llProduced.setVisibility(View.GONE);
        llSurplusProduced.setVisibility(View.GONE);
    }


    @OnClick({R.id.ll_tuandui})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_tuandui:
                break;
        }
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case TEALTIME_INDEX:
                isSoTheMortgage = true;
                if (data != null) {
                    realTimeIndexBean = GsonUtils.fromJson(data.toString(), RealTimeIndexBean.class);
                    if (realTimeIndexBean.getCode() == 0) {
                        RealTimeIndexBean.DataBean dataBean = realTimeIndexBean.getData();
                        if (dataBean != null) {
                            bdSoTheMortgage = new BigDecimal(dataBean.getMgpNum());
                            tvAllNetworkMortgage.setText(dataBean.getMgpNum());
                            tvMortgageValue.setText("$" + dataBean.getMapValue());
                            mappingIndexTv.setText(dataBean.getTransferSpeed());
                        }
                    } else {
                        ToastUtils.showShort(realTimeIndexBean.getMsg());
                    }
                }
                realtimeCirculation();
                break;
            case BALANCE://["161.4881 MGP"]
                String b = "0";
                if (!ObjectUtils.isEmpty(data)) {
                    if (data.toString().contains("MGP")) {
                        b = data.toString().split(" ")[0].replace("[\"", "");
                    }
                }
                balance = new BigDecimal(b);
//                tvCumulativeDestruction.setText(bdCurrencyAmount.subtract(balance).toPlainString());
//                tvOperationAndConstruction.setText(balance.toPlainString());
//                tvEcologicalFund.setText(balance.toPlainString());
//                tvTeamMotivation.setText(balance.toPlainString());
//                tvTotalOrePool.setText(balance.toPlainString());
//                tvAllTotalCoins.setText(balance.toPlainString());
//                tvAllTotalCoinsUsd.setText("$" + balance.multiply(price).toPlainString());
                break;
            case PRICE:
                isPrice = true;
                if (data != null) {
                    EOSPrice eosPrice = (EOSPrice) data;
                    EOSPrice.DataBean dataBean = eosPrice.getData();
                    price = dataBean.getPrice();
                }
                if (price == null) {
                    price = BigDecimal.ZERO;
                }
                tvRealTimePrice.setText("$" + price.toPlainString());
                realtimeCirculation();
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case TEALTIME_INDEX:
                isSoTheMortgage = true;
                realtimeCirculation();
                break;
            case BALANCE://["161.4881 MGP"]
                break;
            case PRICE:
                isPrice = true;
                realtimeCirculation();
                break;
        }
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {

    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(this);
    }

    @Override
    public boolean isShowState() {
        return true;
    }

    public void getCurrencyBalance(Map<String, Object> map, int type) {
        Observable.fromCallable(() -> EOSNetWorkManager.getRpcProvider().getCurrencyBalance(Params.getRequestBody(map)))
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new RxSubscriber<String>(RealTimeDateActivity.this, true) {

                    @Override
                    public void onFail(String failMsg) {
                        String b = "0";
                        switch (type) {
                            case 1:
                                isEcologicalReward = true;
                                bdEcologicalReward = new BigDecimal(b);
                                tvTeamMotivation.setText(b);
                                break;
                            case 2:
                                isNikkoEcoFund = true;
                                bdNikkoEcoFund = new BigDecimal(b);
                                tvEcologicalFund.setText(b);
                                break;
                            case 3:
                                isOperatingFunds = true;
                                bdOperatingFunds = new BigDecimal(b);
                                tvOperationAndConstruction.setText(b);
                                break;
                            case 4:
                                isMagpchain2222 = true;
                                bdMagpchain2222 = new BigDecimal(b);
                                break;
                            case 5:
                                isAccumulativeDestruction = true;
                                bdAccumulativeDestruction = new BigDecimal(b);
                                tvCumulativeDestruction.setText(b);
                                break;
                        }
                        realtimeCirculation();
                    }

                    @Override
                    public void onSuccess(String s) {//["161.4881 MGP"]
                        //地址:mangochain11 生态激励地址 47700000
                        // 地址:mangochain22 生态基金地址  46760000
                        // 地址:mangochain33 运营地址 9769290
                        String b = "0";
                        if (!ObjectUtils.isEmpty(s)) {
                            if (s.contains("MGP")) {
                                b = s.split(" ")[0].replace("[\"", "");
                            }
                        }
                        switch (type) {
                            case 1:
                                isEcologicalReward = true;
                                bdEcologicalReward = new BigDecimal(b);
                                tvTeamMotivation.setText(b);
                                break;
                            case 2:
                                isNikkoEcoFund = true;
                                bdNikkoEcoFund = new BigDecimal(b);
                                tvEcologicalFund.setText(b);
                                break;
                            case 3:
                                isOperatingFunds = true;
                                bdOperatingFunds = new BigDecimal(b);
                                tvOperationAndConstruction.setText(b);
                                break;
                            case 4:
                                isMagpchain2222 = true;
                                bdMagpchain2222 = new BigDecimal(b);
                                break;
                            case 5:
                                isAccumulativeDestruction = true;
                                bdAccumulativeDestruction = new BigDecimal(b);
                                tvCumulativeDestruction.setText(b);
                                break;
                        }
                        realtimeCirculation();
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
